package com.example.heimashop.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.heimashop.model.Address;

import java.util.ArrayList;
import java.util.List;

/**
 * 收货地址数据访问类
 */
public class AddressDao {
    private DatabaseHelper dbHelper;

    public AddressDao(Context context) {
        this.dbHelper = DatabaseHelper.getInstance(context);
    }

    /**
     * 添加地址
     */
    public long addAddress(Address address) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        // 如果设置为默认地址，先将其他地址设为非默认
        if (address.isDefault()) {
            clearDefaultAddress();
        }

        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_CONSIGNEE, address.getConsignee());
        values.put(DatabaseHelper.COLUMN_PHONE, address.getPhone());
        values.put(DatabaseHelper.COLUMN_PROVINCE, address.getProvince());
        values.put(DatabaseHelper.COLUMN_CITY, address.getCity());
        values.put(DatabaseHelper.COLUMN_DISTRICT, address.getDistrict());
        values.put(DatabaseHelper.COLUMN_DETAIL_ADDRESS, address.getDetailAddress());
        values.put(DatabaseHelper.COLUMN_IS_DEFAULT, address.isDefault() ? 1 : 0);

        return db.insert(DatabaseHelper.TABLE_ADDRESS, null, values);
    }

    /**
     * 更新地址
     */
    public int updateAddress(Address address) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        // 如果设置为默认地址，先将其他地址设为非默认
        if (address.isDefault()) {
            clearDefaultAddress();
        }

        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_CONSIGNEE, address.getConsignee());
        values.put(DatabaseHelper.COLUMN_PHONE, address.getPhone());
        values.put(DatabaseHelper.COLUMN_PROVINCE, address.getProvince());
        values.put(DatabaseHelper.COLUMN_CITY, address.getCity());
        values.put(DatabaseHelper.COLUMN_DISTRICT, address.getDistrict());
        values.put(DatabaseHelper.COLUMN_DETAIL_ADDRESS, address.getDetailAddress());
        values.put(DatabaseHelper.COLUMN_IS_DEFAULT, address.isDefault() ? 1 : 0);

        return db.update(DatabaseHelper.TABLE_ADDRESS,
                values,
                DatabaseHelper.COLUMN_ADDRESS_ID + " = ?",
                new String[]{String.valueOf(address.getId())});
    }

    /**
     * 删除地址
     */
    public int deleteAddress(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        return db.delete(DatabaseHelper.TABLE_ADDRESS,
                DatabaseHelper.COLUMN_ADDRESS_ID + " = ?",
                new String[]{String.valueOf(id)});
    }

    /**
     * 获取所有地址
     */
    public List<Address> getAllAddresses() {
        List<Address> addresses = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        // 默认地址排在前面
        Cursor cursor = db.query(DatabaseHelper.TABLE_ADDRESS,
                null, null, null, null, null,
                DatabaseHelper.COLUMN_IS_DEFAULT + " DESC, " +
                DatabaseHelper.COLUMN_ADDRESS_ID + " DESC");

        while (cursor.moveToNext()) {
            addresses.add(cursorToAddress(cursor));
        }
        cursor.close();
        return addresses;
    }

    /**
     * 获取默认地址
     */
    public Address getDefaultAddress() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_ADDRESS,
                null,
                DatabaseHelper.COLUMN_IS_DEFAULT + " = ?",
                new String[]{"1"},
                null, null, null);

        Address address = null;
        if (cursor.moveToFirst()) {
            address = cursorToAddress(cursor);
        }
        cursor.close();
        return address;
    }

    /**
     * 根据ID获取地址
     */
    public Address getAddressById(int id) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_ADDRESS,
                null,
                DatabaseHelper.COLUMN_ADDRESS_ID + " = ?",
                new String[]{String.valueOf(id)},
                null, null, null);

        Address address = null;
        if (cursor.moveToFirst()) {
            address = cursorToAddress(cursor);
        }
        cursor.close();
        return address;
    }

    /**
     * 设置默认地址
     */
    public void setDefaultAddress(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        // 先清除其他默认地址
        clearDefaultAddress();

        // 设置新的默认地址
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_IS_DEFAULT, 1);
        db.update(DatabaseHelper.TABLE_ADDRESS,
                values,
                DatabaseHelper.COLUMN_ADDRESS_ID + " = ?",
                new String[]{String.valueOf(id)});
    }

    /**
     * 清除所有默认地址标记
     */
    private void clearDefaultAddress() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_IS_DEFAULT, 0);
        db.update(DatabaseHelper.TABLE_ADDRESS, values, null, null);
    }

    /**
     * 将Cursor转换为Address对象
     */
    private Address cursorToAddress(Cursor cursor) {
        Address address = new Address();
        address.setId(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ADDRESS_ID)));
        address.setConsignee(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CONSIGNEE)));
        address.setPhone(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_PHONE)));
        address.setProvince(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_PROVINCE)));
        address.setCity(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CITY)));
        address.setDistrict(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_DISTRICT)));
        address.setDetailAddress(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_DETAIL_ADDRESS)));
        address.setDefault(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_IS_DEFAULT)) == 1);
        return address;
    }
}
